package socket1009;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class Server{
    private ArrayList<PrintWriter> arrayList=new ArrayList<PrintWriter>();
    private ServerSocket serverSocket;
    private BufferedReader bfr;

    public Server() {
        try {
            System.out.println("服务端启动中...");
            serverSocket=new ServerSocket(8088);
            System.out.println("服务端启动成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void start(){
        try {
            while (true){
                System.out.println("等待链接");
                Socket accept = serverSocket.accept();
                System.out.println("连接成功");
                Thread thread = new Thread(new ClientHandle(accept));


                thread.start();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandle implements Runnable{
        private Socket accept;

        public ClientHandle(Socket accept){
            this.accept=accept;
        }

        @Override
        public void run() {
            try {
                InputStream stream = accept.getInputStream();
                InputStreamReader isr=new InputStreamReader(stream, StandardCharsets.UTF_8);
                bfr=new BufferedReader(isr);
                OutputStream stream1 = accept.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(stream1,StandardCharsets.UTF_8);
                BufferedWriter bfw=new BufferedWriter(osw);
                PrintWriter writer = new PrintWriter(bfw,true);
                arrayList.add(writer);
                String d;
                while ((d=bfr.readLine())!=null){
                    System.out.println(d);

                    for (PrintWriter z: arrayList) {
                        z.println(d);
                    }
                }
                System.out.println("结束");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
